<template>
  <el-menu default-active="1" class="el-menu-demo" mode="horizontal" @select="handleSelect">
    <h1 style="float: left;line-height: 60px;font-size: 20px;padding: 0 20px">山东财经大学区块链打卡辅助平台</h1>
    <template v-if="clientWidth>600">
      <el-menu-item index="1" style="float:right;margin: 0 5% 0 0;">{{ user_data.name }}</el-menu-item>
      <el-menu-item style="float: right;">
        <el-link href="/#/contact">联系我们</el-link>
      </el-menu-item>
    </template>
    <i v-else class="el-icon-s-fold" style="line-height: 60px;font-size: 1.2rem" @click="drawer=true"></i>
  </el-menu>
  <el-container>
    <el-main>
      <el-row>
        <el-col :xs="{span:24}" :md="{span:9,offset:2}">
          <el-descriptions title="基本信息" direction="vertical" :column="5" border>
            <el-descriptions-item label="姓名">{{ user_data.name }}</el-descriptions-item>
            <el-descriptions-item label="学号">{{ user_data.study_id }}</el-descriptions-item>
            <el-descriptions-item label="居住地" :span="3">{{ user_data.now_address }}</el-descriptions-item>
            <el-descriptions-item label="邮箱" :span="2">{{ user_data.email }}</el-descriptions-item>
            <el-descriptions-item label="密码" :span="3">{{ user_data.password }}</el-descriptions-item>
            <el-descriptions-item label="开始时间" :span="2">{{ user_data.addTime }}</el-descriptions-item>
            <el-descriptions-item label="结束时间" :span="3">
              {{ user_data.expireTime }}<span style="color: #ff5937;font-weight: bold;margin: 0 5px;">*</span>
              <el-popover
                  placement="bottom"
                  :width="200"
                  trigger="click"
              >
                <template #reference>
                  <span class="link_danger">续费</span>
                  <!--                  <el-link type="danger" style="float: right;margin-right: 20px" href="./#">续费</el-link>-->
                </template>
                <!--                <el-row style="margin-bottom: 0.5rem">-->
                <!--                  <el-col :span="16">选择续费时长</el-col>-->
                <!--                  <el-col :span="8"><small style="color: #aaaaaa">3元/月</small></el-col>-->
                <!--                </el-row>-->
                <!--                <el-radio-group style="width: 100%;" v-model="new_tifen" size="mini">-->
                <!--                  <el-row :gutter="0">-->
                <!--                    <el-col :span="6">-->
                <!--                      <el-radio-button :label="1"></el-radio-button>-->
                <!--                    </el-col>-->
                <!--                    <el-col :span="6">-->
                <!--                      <el-radio-button :label="3"></el-radio-button>-->
                <!--                    </el-col>-->
                <!--                    <el-col :span="6">-->
                <!--                      <el-radio-button disabled :label="6"></el-radio-button>-->
                <!--                    </el-col>-->
                <!--                    <el-col :span="6">-->
                <!--                      <el-radio-button disabled :label="12"></el-radio-button>-->
                <!--                    </el-col>-->
                <!--                  </el-row>-->
                <!--                </el-radio-group>-->
                <el-row>
                  <el-col :span="16"><el-input-number
                      :controls="false"
                      v-model="new_tifen" :min="1" :max="10" size="mini"
                      placeholder="输入续费天数"
                  >
                  </el-input-number></el-col>
                  <el-col :span="8" style="text-align: center;"><span style="font-size: 0.8rem;line-height: 28px;">0.08￥/天</span></el-col>
                </el-row>
                <div style="width: 100%;margin-top: 0.5rem">
                  <span class="link_primary" @click="open_dialog">确定</span>
                </div>
              </el-popover>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <el-badge is-dot type="danger" style="padding-right: 10px;">注意</el-badge>
              </template>
              <strong style="color: #ff5937">充值功能是为打码平台续费额度，本站不收取任何费用！请理性使用！</strong>
            </el-descriptions-item>
          </el-descriptions>
          <el-calendar style="margin-top: 20px" :range="[beginDate, endDate]">
            <template #dateCell="{data}">
              <div
                  style="height: 100%;width: 100%;display: flex;justify-content: center;align-items: center;flex-direction: column">
                <p style="">{{ data.day.split('-')[2] }}</p>
                <i class="el-icon-check"
                   style="color: #39ae39;font-weight: bold;margin-top: 1rem"
                   v-if="sign_status[data.day.split('-')[2]]==='1'"></i>
                <i class="el-icon-close"
                   style="color: #ff5937;font-weight: bold;margin-top: 1rem"
                   v-if="sign_status[data.day.split('-')[2]] && sign_status[data.day.split('-')[2]]!=='1'"></i>
              </div>
            </template>
          </el-calendar>
        </el-col>
        <el-col :xs="{span:24}" :md="{span:9,offset: 1}">
          <el-card style="margin: 20px auto 0;"
                   :body-style="{paddingTop:clientWidth>=970?'50px':'10px',paddingBottom:clientWidth>=970?'50px':'10px'}">
            <template #header>
              <span style="font-size: 1.2rem;">系统个人信息</span>
            </template>
            <el-form label-width="5rem" label-position="right">
              <el-form-item label="姓名">
                <el-input disabled :size="input_size" v-model="user_data.name"></el-input>
              </el-form-item>
              <el-form-item label="学号">
                <el-input disabled :size="input_size" v-model="user_data.study_id"></el-input>
              </el-form-item>
              <el-row>
                <el-col :xs="{span:24}" :md="{span:12}">
                  <el-form-item style="text-align: left;">
                    <template #label>
                      <el-tooltip class="item" effect="dark" content="是否进行签到" placement="top">
                        <span style="color: #ff5937;font-weight: bold">启用脚本</span>
                      </el-tooltip>
                    </template>
                    <el-switch :beforeChange="up_active" v-model="user_data.active" active-color="#13ce66"
                               inactive-color="#ff4949">
                    </el-switch>
                  </el-form-item>
                </el-col>
                <el-col :xs="{span:24}" :md="{span:12}">
                  <el-form-item label="性别" style="text-align: left;">
                    <el-radio-group style="width: 100%" disabled v-model="user_data.sex" size="small">
                      <el-radio-button :label="1">男</el-radio-button>
                      <el-radio-button :label="0">女</el-radio-button>
                    </el-radio-group>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-form-item label="家庭住址">
                <el-input :disabled="edit" :size="input_size" v-model="user_data.address"></el-input>
              </el-form-item>
              <el-form-item label="现居地址">
                <el-input :disabled="edit" :size="input_size" v-model="user_data.now_address"></el-input>
              </el-form-item>
              <el-form-item label="本人电话">
                <el-input :disabled="edit" :size="input_size" v-model="user_data.contact"></el-input>
              </el-form-item>
              <el-form-item label="家长电话">
                <el-input :disabled="edit" :size="input_size" v-model="user_data.phone"></el-input>
              </el-form-item>
              <el-form-item label="学院">
                <el-select disabled :size="input_size" v-model="user_data.college_id" style="width: 100%">
                  <el-option v-for="option in $college" :label="option[1]" :value="option[0]"></el-option>
                </el-select>
              </el-form-item>
              <el-row>
                <el-col :xs="{span:24}" :md="{span:24}" :lg="{span:12}">
                  <el-form-item label="省份">
                    <el-select default-first-option @change="get_city" :size="input_size"
                               v-model="user_data.province_id"
                               style="width: 100%">
                      <el-option v-for="option in $province" :label="option[1]" :value="option[0]"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :xs="{span:24}" :md="{span:24}" :lg="{span:12}">
                  <el-form-item label="城市" required>
                    <el-select :size="input_size" v-model="user_data.city_id" style="width: 100%"
                               :loading="city_loading">
                      <el-option v-for="option in city_list" :label="option[1]" :value="option[0]"></el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <el-row>
              <el-col :span="18" style="text-align: right">
              </el-col>
              <el-col :span="6" style="text-align: right">
                <el-button type="success" size="medium" plain="" @click="save">保存</el-button>
              </el-col>
            </el-row>
          </el-card>
        </el-col>
      </el-row>
    </el-main>
  </el-container>
  <el-dialog
      title="支付宝支付"
      v-model="dialogVisible"
      :before-close="close_dialog"
      top="20px"
      width="80%">
    <iframe id="frame" v-if="dialogVisible" width="100%" height="600px"
            :src="'http://i.chaojiying.com/pay/alipay2016/alipayapi.php?aid=46827&amm='+new_tifen*3"
            frameborder="0"></iframe>
  </el-dialog>
  <el-drawer
      v-if="clientWidth<600"
      :with-header="false"
      v-model="drawer">
    <div style="height: 100vh;text-align: center;width: 100%">
      <div style="margin: 2rem 0">
        <el-image :src="logoUrl"></el-image>
      </div>
      <div>
        <p style="font-size: 1.2rem;line-height: 1rem;color: #2a2a2a">{{ user_data.name }}</p>
        <el-link href="/#/contact" style="margin: 3rem 0;font-size: 1rem">联系我们</el-link>
      </div>
    </div>
  </el-drawer>
</template>

<script>

export default {
  name: "backend",
  data() {
    return {
      user_data: '',
      input_size: 'mini',
      sign_status: '',
      beginDate: [],
      endDate: [],
      dialogVisible: false,
      flag: false,
      already: false,
      drawer: false,
      new_tifen: 1,
      timer: null,
      clientWidth: document.body.clientWidth,
      logoUrl: require('@/assets/logo.png')
    }
  },
  methods: {
    get_city(province_id) {
      let str = ''
      this.user_data.city_id = '0'
      this.$axios({
        url: '/api/get_city',
        params: {
          province_id: province_id
        },
      }).then((res) => {
        str = res.data
        const reg = /<option.*?option>/g
        const value_reg = /[0-9]{1,3}/
        const label_reg = />.*?</
        const options = str.match(reg)
        const list = []
        for (const option of options) {
          let value = option.match(value_reg)[0]
          let label = option.match(label_reg)[0]
          label = label.slice(1, label.length - 1)
          list.push([value, label])
        }
        this.city_list = list
      })
    },
    get_data() {
      this.$axios({
        url: '/api/user/info',
        params: {
          id: JSON.parse(localStorage['user_data'])['study_id']
        },
      }).then((res) => {
        this.user_data = JSON.parse(JSON.stringify(res.data))
        localStorage['server_data'] = JSON.stringify(res.data)
        this.user_data['province_id'] = this.user_data['province_id'].toString()
        this.user_data['college_id'] = this.user_data['college_id'].toString()
        this.get_city(this.user_data['province_id'])
        this.user_data['city_id'] = res.data['city_id'].toString()
        this.user_data['active'] = this.user_data['active'] === 1
      })
      this.$axios.get('/api/notify?n_id=latest').then((res) => {
        this.$notify({
          title: res.data.title,
          dangerouslyUseHTMLString: true,
          message: res.data.content + "<div style='width: 100%;text-align: left;'><a href='/#/notify/all' style='color: #409EFF'>查看全部</a></div>",
          type: 'info',
          duration: 0
        });
      })
    },
    check_sign() {
      this.$axios.get('/api/sign/status').then((res) => {
        this.sign_status = res.data
      }).catch((res) => {
        this.$ElMessage.warning({
          message: '登录已失效，请重新登录'
        })
        setTimeout(() => {
          this.$router.push('/')
        }, Math.random() * 1000)
      })
    },
    getTargetDate() {
      const now = new Date()
      this.endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7)
      if (this.endDate.getMonth() !== now.getMonth() && now.getDay() !== 6) {
        this.endDate = new Date(now.getFullYear(), now.getMonth() + 1, 1)
      }
      this.beginDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 14)
    },
    open_dialog() {
      location.href = 'http://yq.py00.top/codepay/codepay.php?price=' + this.new_tifen*0.08 + '&pay_id=' + this.user_data.study_id
      // this.$router.push('http://yq.py00.top/codepay/codepay.php?price=0.01&pay_id=20191874148')
      // let last_tifen = ''
      // this.timer = setInterval(() => {
      //   let url = '/api/getScore'
      //   this.$axios.get(url).then((res) => {
      //     let now_tifen = res.data['tifen']
      //     if (!this.flag) {
      //       last_tifen = now_tifen
      //       this.flag = true
      //     } else {
      //       if (now_tifen - last_tifen >= this.new_tifen * 1000 - 200) {
      //         clearInterval(this.timer)
      //         let time = new Date(Math.max(new Date(), new Date(this.user_data['expireTime'])))
      //         let targetTime = new Date(time.setDate(time.getDate() + this.new_tifen * 30))
      //         if (!this.already) {
      //           this.already = true
      //           this.$axios.post('/api/update/score', {
      //             id: this.user_data.study_id,
      //             up_time: this.new_tifen,
      //             targetTime: targetTime
      //           }).then((res) => {
      //             this.dialogVisible = false
      //             this.get_data()
      //             this.$ElMessage({
      //               message: '充值成功',
      //               type: 'success'
      //             })
      //           })
      //         }
      //       }
      //     }
      //   })
      // }, 300)
      // this.dialogVisible = true
    },
    close_dialog(done) {
      clearInterval(this.timer)
      done()
    },
    save() {
      this.$axios.post('/api/save/info', this.user_data).then((res) => {
        if (res.data) {
          this.get_data()
          this.$ElMessage({
            message: '保存成功',
            type: 'success'
          })
        } else {
          this.$ElMessage({
            message: '保存失败',
            type: 'error'
          })
        }
      })
    },
    up_active() {
      this.$axios.post('/api/up/active', {
        school_id: this.user_data.school_id,
        active: !this.user_data.active
      }).then((res) => {
        if (res.data === 0) {
          this.$ElMessage.success({message: '已开启签到'})
        } else if (res.data === 1) {
          this.$ElMessage.error({message: '已关闭签到'})
        } else {
          this.$ElMessage.error({message: '修改失败'})
        }
        this.user_data.active = !this.user_data.active
      }).catch((res) => {
        this.$ElMessage.error({message: '修改失败'})
      })
    }
  },
  mounted() {
    this.getTargetDate()
    this.get_data()
    this.check_sign()
    window.onresize = () => {
      this.clientWidth = document.body.clientWidth
    }
  },
}
</script>

<style lang="less" scoped>
.link_danger {
  color: #F56C6C;
  margin: 0 10px;

  &:hover {
    text-decoration: underline;
    cursor: pointer;
  }
}

.link_primary {
  color: #409EFF;
  float: right;
  margin-right: 5px;

  &:hover {
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>